# -*- coding:UTF-8 -*-
import util
import cv2
import epic_operator as eo
import time
import random
import config
import logger
import sys
tmp=''
is_shuqian=0
def getImageData(conf):
    imgPath=config.imgPath
    for k in conf:
        # if "is_img" in conf[k].keys():
     
        #     continue
        # print(k)
        # sys.exit()
        conf[k]['key']=k
        # data.append({'name':event,'data':cv2.imread(imgPath+event+'.png',0)})
        # conf[k]['data']=cv2.imread(imgPath+k+'.png',0)
        if "img" in conf[k].keys():
            conf[k]['data']=cv2.cvtColor( cv2.imread(imgPath+conf[k]['img']), cv2.COLOR_BGR2GRAY)
        else:      
            conf[k]['data']=cv2.cvtColor( cv2.imread(imgPath+k+'.png'), cv2.COLOR_BGR2GRAY)
    return conf       
#刷讨伐     
def loopTaofa(data,is_end=0):
    looppro(data,is_end)
#刷支线    
def loopZhiXian(data,is_end=0):
    looppro(data,is_end) 
#刷月塔    
def loopShuaTa(data,is_end=0):
    looppro(data,is_end) 
def loopMaoxian94(data,is_end=0):
    # is_war_start=0
    global tmp  
    tmp=eo.get_screen()
    index=0   
    east94Imgdata=getImgData("94east.png")
    west94Imgdata=getImgData("94west.png")
    yaoshuiImgData=getImgData('maoxian_yaoshui.png')
    route=getImageData(config.maoxian94Route) 
    # print(route) 
    # sys.exit()
    tmpret=0
    while(1):
             for i in data:
                ret=findAndClickByPos(data[i])
                #  print(ret)
                if ret=='taofa_battle_start1' or ret =='taofa_battle_start':
                    tmpret=ret 
             if tmpret=='taofa_battle_start1' or tmpret =='taofa_battle_start':
                break   
             eo.get_randtime(1,2)   
             tmp=eo.get_screen()
          
    while(1):            
        # ret=findAndClickByPos(route[str(index)])
        if index==4:
            ret=eo.matchPos(east94Imgdata,tmp)
            if ret!=0:
                eo.click(99,66)
                eo.get_randtime(1,2)
                eo.swipe(510,150,210,350)
                tmp=eo.get_screen()
                findAndClickByPos(createImgDict("94chuansong.png","[点击传送]按钮"))
                findAndClickByPos(createImgDict("shop_confirm.png",'[点击确认]按钮'))
        elif index==7:
            ret=eo.matchPos(west94Imgdata,tmp)
            if ret!=0:
                eo.click(99,66)
                eo.get_randtime(1,2)
                tmp=eo.get_screen()  
                findAndClickByPos(createImgDict("94chuansong.png","[点击传送]按钮"))
                findAndClickByPos(createImgDict("shop_confirm.png",'[点击确认]按钮'))
                eo.click(470,255)
                eo.get_randtime(1,2)
                tmp=eo.get_screen()
                findAndClickByPos(createImgDict("94endbattle.png",'[点击探险结束]按钮'))
                eo.get_randtime(2,3)
                break
        else :
             ret=findAndClickByPos(route[str(index)])
        # print(ret)     
        if ret!=0:
            index=index+1
        # print(index)         
        eo.get_randtime(1,2)
        tmp=eo.get_screen()    
def createImgDict(img,name,key='default'):
    return {'x':1,'y':1,'time':1,'name':name,'data':getImgData(img),'key':key}
def getImgData(img):
    return  cv2.cvtColor( cv2.imread(config.imgPath+img), cv2.COLOR_BGR2GRAY)           
def loopRefreshShop(data,is_end=0):  
    global tmp  
    while(1):       
        tmp=eo.get_screen()
        findAndClick(data['paiqian_finish'])
        getShuqian(data,"shop_shuqian","shop_buy")
        getShuqian(data,"shop_shenmi","shop_buy")
        if is_shuqian==1:
            break
        else:
            eo.swipe()
            eo.get_randtime(1,2)
            tmp=eo.get_screen()    
        getShuqian(data,"shop_shuqian","shop_buy")
        getShuqian(data,"shop_shenmi","shop_buy")
        findAndClick(data['shop_refresh'])
        re=findAndClick(data['shop_confirm'])
        if re==1:
            break
#查找书签有则领取，没有则返回
# param findShuqian 发现书签的操作
# param confirm 确定按钮
# return 0不进行 1进行重复操作   
def getShuqian(data,findShuqian,confirm,tcache=''):
    # print(data)
    clickByFind(data[findShuqian],tcache=tcache)
    findAndClick(data[confirm],tcache=tcache)      
#根据查找的图片位置进行点击    
def clickByFind(value,offset=30,tcache=''):
    global tmp,is_shuqian  
    re=eo.matchPos(value['data'],tmp)
    if re!=0:
        if value['key']=="shop_shuqian" or value['key']=="shop_shenmi":
           is_shuqian=is_shuqian+1
        elif is_shuqian<3 and is_shuqian>0:
           return 1   
   
        logger.info(value['name']+"匹配")
        y=re[3][1]+offset  
        handClick(value['x'],[y,y+value['y']])    
        eo.get_randtime(value['time'],value['time']+1)
        tmp=eo.get_screen()
        return 1
    return 0
def findAndClickByPos(value,xoffset=0,yoffset=0):
    global tmp
    re=eo.matchPos(value['data'],tmp) 
    if re!=0:
        logger.info(value['name']+"匹配")
        if isinstance(value['x'],list):
           x=[value['x'][0]+xoffset,value['x'][1]+xoffset]
        else:
            #如果value[x]不是元组那就是范围值  
          x=[re[3][0]+xoffset,re[3][0]+xoffset+value['x']]   
        if isinstance(value['y'],list):
          y=[value['y'][0]+yoffset,value['y'][1]+yoffset]
        else:
          #如果value[y]不是元组那就是范围值  
          y=[re[3][1]+yoffset,re[3][1]+yoffset+value['y']]    
        handClick(x,y)    
        eo.get_randtime(value['time'],value['time']+1)
        tmp=eo.get_screen()      
        return value['key']
    return 0           
def findAndClick(value,tcache=''):
    global tmp,is_shuqian  
    re=eo.match(value['data'],tmp)
    if re==1:
        time=0
        if value['key']=="shop_buy":
            is_shuqian=0
            time=1       #防止页面刷新不够时间导致的问题
        if is_shuqian<3 and is_shuqian>0:
            return 1   
        elif value['key'] =="shop_confirm":
            is_shuqian=0
            time=1             
        logger.info(value['name']+"匹配")  
        handClick(value['x'],value['y'])    
        eo.get_randtime(value['time']+time,value['time']+time+2)
        tmp=eo.get_screen()
        return 1
    return 0    
#循环配置                         
def looppro(data,is_end=0):              
    tmp=eo.get_screen()
    for key in data:
         value=data[key]
         re=eo.match(value['data'],tmp)
         if re==1: 
            if 'is_end' in value and value['is_end']==1:
                is_end+=1 
            #等待一秒多再点击  
            logger.info(value['name']+"匹配")  
            # eo.get_randtime(1,2)    
            handClick(value['x'],value['y'])    
            #点击后需要停顿时间
            eo.get_randtime(value['time'],value['time']+2)
            break
    if is_end<1:
        eo.get_randtime(5,6) 
        looppro(data,is_end)      
def handClick(x,y):
     sx, sy = eo.get_randxy(x,y)
     eo.click(sx, sy)


